package com.nidu.demo.notify.executor.command;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.enums.UserTypeEnum;
import com.nidu.demo.notify.ability.NotifyTemplateDomainService;
import com.nidu.demo.notify.convertor.NotifyMessageConvertor;
import com.nidu.demo.notify.dto.NotifyMessageCO;
import com.nidu.demo.notify.dto.NotifyMessageSendCmd;
import com.nidu.demo.notify.dto.NotifyTemplateCO;
import com.nidu.demo.notify.gateway.NotifyMessageGateway;
import com.nidu.demo.notify.model.NotifyMessage;
import com.nidu.demo.notify.model.NotifyMessageCriteria;
import com.nidu.demo.notify.model.NotifyTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 站内信新增执行器
 *
 * @author auto
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class NotifyMessageAddCmdExe {

    private final NotifyMessageConvertor convertor;

    private final NotifyMessageGateway gateway;

    private final NotifyTemplateDomainService templateDomainService;

    public Response execute(UserTypeEnum userType, NotifyMessageSendCmd cmd) {
        NotifyTemplate notifyTemplate = templateDomainService.validateNotifyTemplate(cmd.getTemplateCode());

        templateDomainService.validateTemplateParams(notifyTemplate, cmd.getTemplateParams());

        String content = notifyTemplate.formatTemplateContent(notifyTemplate.getTemplateContent(), cmd.getTemplateParams());

        NotifyMessage notifyMessage = NotifyMessage.create(cmd.getUserId(), userType.getType(), notifyTemplate.getId(), notifyTemplate.getTemplateCode(),
                notifyTemplate.getTemplateNickname(), content, notifyTemplate.getTemplateType(), cmd.getTemplateParams());

        gateway.create(notifyMessage);
        return Response.buildSuccess();
    }

    @Transactional
    public Response execute(UserTypeEnum userType, Set<Long> userIds, NotifyMessageSendCmd cmd) {
        NotifyTemplate notifyTemplate = templateDomainService.validateNotifyTemplate(cmd.getTemplateCode());

        templateDomainService.validateTemplateParams(notifyTemplate, cmd.getTemplateParams());

        String content = notifyTemplate.formatTemplateContent(notifyTemplate.getTemplateContent(), cmd.getTemplateParams());

        userIds.forEach(id -> {
            NotifyMessage notifyMessage = NotifyMessage.create(id, userType.getType(), notifyTemplate.getId(), notifyTemplate.getTemplateCode(),
                    notifyTemplate.getTemplateNickname(), content, notifyTemplate.getTemplateType(), cmd.getTemplateParams());
            gateway.create(notifyMessage);
        });
        return Response.buildSuccess();
    }

}
